package www.study.com;

//删除链表的倒数第 N 个结点 https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
public class code18 {
    public static void main(String[] args) {

    }

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */

     class ListNode {
         int val;
         ListNode next;
         ListNode() {}
         ListNode(int val) { this.val = val; }
         ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     }
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode rig = head;
            for(int i = 0 ; i < n && rig != null ; i++){
                rig = rig.next;
            }
            if(rig == null){ //特殊：删除头节点
                rig = head.next;
                head.next = null;
                return rig;
            }
            //通常：删除非头节点（中间节点 或者 尾节点）
            ListNode now = head;
            ListNode pre = null;
            while(rig != null){
                rig = rig.next;
                pre = now;
                now = now.next;
            }
            pre.next = now.next;
            now.next = null;
            return head;
        }
    }
}
